<template>
  <div>
    <a-card>
      <h2 v-if="!isSimple">操作日志</h2>
      <h3 v-else>最近操作日志</h3>
      <a-divider />
      <!-- 操作日志表格 -->
      <a-spin :spinning="loading">
        <a-table
          :dataSource="loglist"
          :columns="columns"
          :pagination="false"
          bordered
        >
          <template #createdAt="data">
            {{ formateTimestamp(data.record.meta.createdAt) }}
          </template>
          <template v-if="!isSimple" #operation="data">
            <a @click="deleteLog(data.record._id)">删除</a>
          </template>
        </a-table>
      </a-spin>
      <div class="mt-10">
        <a-pagination
          v-if="!isSimple"
          v-model:current="curPage"
          :page-size="pageSize"
          :total="total"
          @change="setPage"
        ></a-pagination>
      </div>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from 'vue'
import { handleResult, formateTimestamp } from '../helpers/utils'
import { logService } from '../services'
import { getLogInfoByPath } from '../helpers/log'
import { message } from 'ant-design-vue'

export default defineComponent({
  props: {
    simple: Boolean
  },
  setup (props) {
    const curPage = ref(1)
    const total = ref(0)
    const pageSize = ref(5)
    const loglist = ref([])
    const columns = [
      {
        title: '用户名称',
        dataIndex: 'user.username'
      },
      {
        title: '访问地址',
        dataIndex: 'action'
      },
      {
        title: '开始时间',
        slots: {
          customRender: 'createdAt'
        }
      }
    ]
    if (!props.simple) {
      columns.push({
        title: '操作',
        slots: {
          customRender: 'operation'
        }
      })
    }

    /** 分页组件页码变化事件 */
    const setPage = page => {
      curPage.value = page
      getLoglist()
    }

    const getLoglist = async () => {
      loading.value = true
      const res = await logService.list(curPage.value, pageSize.value)
      handleResult(res).success(({ data: { list, total: t } }) => {
        list.forEach(item => {
          item.key = item._id
          item.action = getLogInfoByPath(item.request.url)
        })
        loglist.value = list
        total.value = t
        loading.value = false
      })
    }

    onMounted(async () => {
      getLoglist()
    })

    /** 删除某条日志 */
    const deleteLog = async logId => {
      const res = await logService.deleteLog(logId)
      handleResult(res).success(({ msg }) => {
        message.success(msg)
      })
    }

    const loading = ref(true)
    return {
      curPage,
      pageSize,
      total,
      columns,
      loglist,
      setPage,
      loading,
      formateTimestamp,
      deleteLog,
      isSimple: props.simple
    }
  }
})
</script>

<style lang="scss" scoped></style>
